package com.cmw.socket.l_2_3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(2000);
        System.out.println("服务器准备就绪...");
        System.out.println("服务器端信息："+server.getInetAddress()+", 端口号："+server.getLocalPort());
        //等待客户端连接
        for(;;){
            //得到客户端
            Socket client = server.accept();
            //构建客户端异步线程
            ClientHandler clientHandler = new ClientHandler(client);
            //启动线程
            clientHandler.start();
        }
    }

    /**
     * 客户端消息处理类
     */
    static class ClientHandler extends Thread{
        private Socket socket;
        private boolean flag = true;

        ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            super.run();
            System.out.println("新客户端连接："+socket.getInetAddress()+",端口号："+socket.getPort());
            try {
                //得到打印流，用于数据输出；服务器回送数据
                PrintStream socketOutput = new PrintStream(socket.getOutputStream());
                //得到输入流，用于接收数据
                BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                do{
                    //客户端拿到一条数据
                    String str = socketInput.readLine();
                    if(null != str && str.equalsIgnoreCase("bye")){
                        flag = false;
                        socketOutput.println("bye");
                    }else{
                        System.out.println(str);
                        socketOutput.println("回送："+str+"["+str.length()+"]");
                    }
                }while (flag);
                socketOutput.close();
                socketInput.close();
            } catch (IOException e) {
                System.out.println("客户端连接异常...");
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("客户端已退出："+socket.getInetAddress()+",端口号："+socket.getPort());
        }
    }
}
